//
//  MGTabPageTableView.m
//  Mango
//
//  Created by 胡超 on 2020/6/29.
//  Copyright © 2020 HuChao. All rights reserved.
//

#import "MGTabPageTableView.h"
#import "MGTabPageView.h"
#import "MGTabPageScrollAdapter.h"
#import "UIView+Mango.h"
#import "Macros.h"

@interface MGTabPageTableView() <MGTabPageViewDelegate> {
    MGTableViewCell *_pageViewCell;
    MGTabPageView *_pageView;
    BOOL _canScroll;
    CGFloat _topOffset;
    
    NSMutableArray *_scrollAdapters;
}
@end

@implementation MGTabPageTableView

- (void)dealloc {
    [self removeObserver:self forKeyPath:@"bounds"];
}

- (instancetype)initWithFrame:(CGRect)frame style:(UITableViewStyle)style {
    return [self initWithFrame:frame style:style topOffset:0];
}

- (instancetype)initWithFrame:(CGRect)frame style:(UITableViewStyle)style tabPageBarStyle:(MGTabPageBarStyle *)tabPageBarStyle {
    return [self initWithFrame:frame style:style topOffset:0 tabPageBarStyle:tabPageBarStyle];
}

- (instancetype)initWithFrame:(CGRect)frame style:(UITableViewStyle)style topOffset:(CGFloat)topOffset {
    return [self initWithFrame:frame style:style topOffset:topOffset tabPageBarStyle:nil];
}

- (instancetype)initWithFrame:(CGRect)frame style:(UITableViewStyle)style topOffset:(CGFloat)topOffset tabPageBarStyle:(MGTabPageBarStyle *)tabPageBarStyle {
    if (self = [super initWithFrame:frame style:style]) {
        self.showsVerticalScrollIndicator = NO;
        self.showsHorizontalScrollIndicator = NO;
        self.directionalLockEnabled = YES;
        if (@available(iOS 11.0, *)) {
            self.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
        }
        
        WeakSelf(wkself)
        [self addObserver:self forKeyPath:@"bounds" options:NSKeyValueObservingOptionNew context:nil];
        [self addSection:^(MGTableViewSection * _Nonnull section) {
            [section setHeightForHeader:0.0f];
            [section setHeightForFooter:0.0f];
            [section addCustomCell:[wkself pageViewCellWithTopOffset:topOffset tabPageBarStyle:tabPageBarStyle]];
        }];
        
        _canScroll = YES;
        _topOffset = topOffset;
        _scrollAdapters = [[NSMutableArray alloc] init];
        [NSNotificationCenter.defaultCenter addObserver:self
                                               selector:@selector(onNotificationParentCanScroll:)
                                                   name:@"MGParentCanScrollNotification"
                                                 object:nil];
    }
    return self;
}

- (void)setBackgroundColor:(UIColor *)backgroundColor {
    [super setBackgroundColor:backgroundColor];
    _pageView.backgroundColor = backgroundColor;
}

- (void)addSection:(void(^)(MGTableViewSection *section))sectionConfiguration {
    if (self.sections.count == 0) {
        [super addSection:sectionConfiguration];
    } else {
        [self insertSectionAtIndex:self.sections.count-1 sectionConfiguration:sectionConfiguration];
    }
}

- (void)setPages:(NSArray *)pages titles:(NSArray<NSString*> *)titles parent:(nullable UIViewController *)parent {
    [_pageView setPages:pages titles:titles parent:parent];
}

- (void)removeAllPages {
    [_pageView removeAllPages];
    [_scrollAdapters removeAllObjects];
}

- (MGTableViewCell *)pageViewCellWithTopOffset:(CGFloat)topOffset tabPageBarStyle:(MGTabPageBarStyle *)tabPageBarStyle {
    if (_pageViewCell == nil) {
        _pageViewCell = [[MGTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:nil];
        _pageViewCell.cellHeight = self.frame.size.height-topOffset;
        _pageViewCell.selectionStyle = UITableViewCellSelectionStyleNone;
        
        _pageView = [[MGTabPageView alloc] initWithFrame:CGRectMake(0, 0, self.width, _pageViewCell.cellHeight) style:tabPageBarStyle];
        _pageView.delegate = self;
        [_pageViewCell.contentView addSubview:_pageView];
    }
    return _pageViewCell;
}

- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer {
    if ([otherGestureRecognizer.view isKindOfClass:NSClassFromString(@"MGTabPageContentScrollView")] ||
        [otherGestureRecognizer isKindOfClass:NSClassFromString(@"UIScrollViewPanGestureRecognizer")] == NO) {
        return NO;
    } else {
        return YES;
    }
}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context {
    if (_pageViewCell.cellHeight != self.bounds.size.height) {
        _pageViewCell.cellHeight = self.bounds.size.height;
        _pageView.height = _pageViewCell.cellHeight;
        [self reloadData];
    }
}

#pragma mark - MGTabPageViewDelegate

- (void)tabPageView:(MGTabPageView *)tabPageView didAddPage:(id)page {
    id<MGTabPageScrollAdapterDelegate> delegate = page;
    if ([delegate respondsToSelector:@selector(scrollViewForTabPageScrollAdapter)]) {
        UIScrollView *scrollView = [delegate scrollViewForTabPageScrollAdapter];
        MGTabPageScrollAdapter *scrollAdapter = [[MGTabPageScrollAdapter alloc] initWithScrollView:scrollView];
        [_scrollAdapters addObject:scrollAdapter];
    }
}

- (void)tabPageView:(MGTabPageView *)tabPageView didSelectPageAtIndex:(NSInteger)atIndex {
    
}

#pragma mark - 处理联动

- (void)onNotificationParentCanScroll:(NSNotification *)notification {
    _canScroll = [notification.object boolValue];
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    if (!_canScroll) {
        // 始终停留在固定状态位置
        scrollView.contentOffset = CGPointMake(0, -(_topOffset-_pageViewCell.top));
        return;
    }
    [super scrollViewDidScroll:scrollView];
    
    CGFloat rate = 2.0 - (MIN(MAX(1,-(scrollView.contentOffset.y-_pageViewCell.top)/_topOffset), 2));
    id <MGTabPageTableViewScrollDelegate> delegate = self.scrollViewDelegate;
    if ([delegate respondsToSelector:@selector(scrollViewShouldUpdateNavigationBar:)]) {
        [delegate scrollViewShouldUpdateNavigationBar:rate];
    }

    if (scrollView.contentOffset.y-_pageViewCell.top >= -_topOffset) {
        scrollView.contentOffset = CGPointMake(0, -(_topOffset-_pageViewCell.top));
        [NSNotificationCenter.defaultCenter postNotificationName:@"MGChildCanScrollNotification" object:@(YES)];
        [NSNotificationCenter.defaultCenter postNotificationName:@"MGShouldScrollToTopNotification" object:scrollView];
    } else {
        [NSNotificationCenter.defaultCenter postNotificationName:@"MGChildCanScrollNotification" object:@(NO)];
    }
    
}

@end

